#!/bin/bash

# 获取当前脚本所在的绝对路径
curdir=$(cd "$(dirname "$0")"; pwd -P)

# 加载配置文件
source "$curdir"/openvpn.env

systemctl stop firewalld.service

yum -y install easy-rsa-3.0.8 openvpn-2.4.12 openssl expect

mkdir -p /opt/easy-rsa

rm -rf /opt/easy-rsa/*

cd /opt/easy-rsa

cp -af /usr/share/easy-rsa/3.0.8/* /opt/easy-rsa/

cp -af /usr/share/doc/easy-rsa-3.0.8/vars.example /opt/easy-rsa/vars

cat <<EOF > /opt/easy-rsa/vars
if [ -z "\$EASYRSA_CALLER" ]; then
    echo "You appear to be sourcing an Easy-RSA 'vars' file." >&2
    echo "This is no longer necessary and is disallowed. See the section called" >&2
    echo "'How to use this file' near the top comments for more details." >&2
    return 1
fi
set_var EASYRSA_DN "cn_only"
set_var EASYRSA_REQ_COUNTRY "CN"
set_var EASYRSA_REQ_PROVINCE "Beijing"
set_var EASYRSA_REQ_CITY "Shanghai"
set_var EASYRSA_REQ_ORG "koten"
set_var EASYRSA_REQ_EMAIL "888888@qq.comm"
set_var EASYRSA_NS_SUPPORT "yes"
EOF


touch /tmp/temp_easy_rsa.exp
chmod +x /tmp/temp_easy_rsa.exp


/opt/easy-rsa/easyrsa init-pki

sudo cat <<EOF > /tmp/temp_easy_rsa.exp
#!/usr/bin/expect
spawn /opt/easy-rsa/easyrsa build-ca
expect "Enter New CA Key Passphrase: "
send "$OPENVPN_PASSWORD\r"
expect "Re-Enter New CA Key Passphrase: "
send "$OPENVPN_PASSWORD\r"
expect "Common Name (eg: your user, host, or server name)"
send "server\r"
expect eof
EOF
/tmp/temp_easy_rsa.exp


echo -e "server" | /opt/easy-rsa/easyrsa gen-req server nopass


sudo cat <<EOF > /tmp/temp_easy_rsa.exp
#!/usr/bin/expect
spawn /opt/easy-rsa/easyrsa sign server server
expect "Type the word 'yes' to continue, or any other input to abort."
send "yes\r"
expect "Enter pass phrase for /opt/easy-rsa/pki/private/ca.key:"
send "$OPENVPN_PASSWORD\r"
expect eof
EOF
/tmp/temp_easy_rsa.exp

/opt/easy-rsa/easyrsa gen-dh

echo -e "client" | /opt/easy-rsa/easyrsa gen-req client nopass

sudo cat <<EOF > /tmp/temp_easy_rsa.exp
#!/usr/bin/expect
spawn /opt/easy-rsa/easyrsa sign client client
expect "Type the word 'yes' to continue, or any other input to abort."
send "yes\r"
expect "Enter pass phrase for /opt/easy-rsa/pki/private/ca.key:"
send "$OPENVPN_PASSWORD\r"
expect eof
EOF
/tmp/temp_easy_rsa.exp

rm -f /tmp/temp_easy_rsa.exp

bash "$curdir"/save_conf.sh

cp /etc/openvpn/server.conf /etc/openvpn/server.conf.bak
